﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using RN.ERP.Web;
using RN.ERP.Web.ModelService;
using System.Web.SessionState;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// OuterLoginHandler 的摘要说明
    /// </summary>
    public class OuterLoginHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string userGuid = context.Request.QueryString["u"];
            string action = context.Request.QueryString["a"];
            string parameters = context.Request.QueryString["p"];
            BasicService.BasicServiceClient client = new BasicService.BasicServiceClient();
            RN.ERP.Web.ModelService.UserInfo userInfo = JsonConvert.DeserializeObject<RN.ERP.Web.ModelService.UserInfo>(client.DoLoginWithUGuid(userGuid, string.Empty, HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString()));
            if (userInfo.Result)
            {
                SessionUserInfo sui = new SessionUserInfo();
                sui.UserName = userInfo.UserName;
                sui.Name = userInfo.Name;
                sui.CorpUserGuid = userInfo.UserGuid;
                sui.DogId = userInfo.DogId;
                sui.RoleId = userInfo.RoleId;
                sui.FuncPerm = userInfo.FuncPerm;
                sui.AreaCode = userInfo.AreaCode;
                sui.LocalArea = userInfo.AreaCode2;
                sui.RoleType = userInfo.RoleType;
                sui.RoleTypeTitle = userInfo.RoleTypeTitle;
                sui.CurrentArea = string.IsNullOrEmpty(userInfo.AreaCode) ? string.Empty : userInfo.AreaCode.Substring(0, 2);
                HttpContext.Current.Session[SessionConstant.SESSION_USERINFO] = sui;
                ////当前市场范围，暂时处理,外地企业则需要首次登陆时确定市场范围
                ////用SessionUserInfo.CurrentArea替代。
                ////HttpContext.Current.Session[SessionConstant.SESSION_CURRENT_AREACODE] = userInfo.AreaCode;
                context.Response.Redirect(RouteUrl(action, parameters));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string RouteUrl(string action, string parameters)
        {
            switch (action.ToLower())
            {
                case "ca01":
                    return "../ca/CAOrderList.aspx?group=CA01";
                default:
                    return "../login.aspx";
            }
        }
    }
}